package com.ljkj.cordial.chat.ui.views;

import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.base.Dto;
import com.lanjiu.lib.imclient.dto.user.RegisteredUserDto;
import com.lanjiu.lib.imclient.dto.user.TouristsUserDto;
import com.lanjiu.lib.imclient.dto.user.UserDto;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.log.Logger;
import com.ljkj.cordial.chat.ui.IView;

/**
 * @description:
 * @author: Panwei
 * @date: 2019/11/22 10:11
 */
public class PersonalView extends IView {

    private PersonalCallback mCallback;

    public PersonalView(PersonalCallback mCallback) {
        this.mCallback = mCallback;
    }

    public void doModifyPhoto(String photo) {
        int action;
        String data;
        if (UserPreferences.isRegistered()) {
            action = EventConstants.Action.PERSONAL_AVATAR_REGISTERED;
            RegisteredUserDto registeredUser = new RegisteredUserDto();
            registeredUser.setUserId(UserPreferences.getUserId());
            registeredUser.setAvatar(photo);
            data = registeredUser.toJson();
        } else {
            action = EventConstants.Action.PERSONAL_AVATAR_TOURISTS;
            TouristsUserDto touristsUser = new TouristsUserDto();
            touristsUser.setTemporaryId(UserPreferences.getUserId());
            touristsUser.setNickname(photo);
            data = touristsUser.toJson();
        }
        doSendRequest(action, data);
    }

    @Override
    public void onMessageEventHandle(MessageEvent event) {
        Logger.print("PersonalView", event.toString());
        if (event.action() == EventConstants.Action.PERSONAL_AVATAR_TOURISTS) {
            // 游客修改头像
            UserDto user = null;
            if (checkIsSuccess(event.code(), event.data())) {
                TouristsUserDto touristsUser = Dto.fromJson(event.data(), TouristsUserDto.class);
                if (null != touristsUser) user = new UserDto(touristsUser);
            }
            if (null != mCallback)
                mCallback.onModifyPhotoCallback(event.code(), event.msg(), user);
        } else if (event.action() == EventConstants.Action.PERSONAL_AVATAR_REGISTERED) {
            // 注册用户修改头像
            UserDto user = null;
            if (checkIsSuccess(event.code(), event.data())) {
                RegisteredUserDto registeredUser = Dto.fromJson(event.data(), RegisteredUserDto.class);
                if (null != registeredUser) user = new UserDto(registeredUser);
            }
            if (null != mCallback)
                mCallback.onModifyPhotoCallback(event.code(), event.msg(), user);
        }
    }

    public interface PersonalCallback {

        void onModifyPhotoCallback(int code, String msg, UserDto data);
    }
}
